import React, {Component} from 'react'
import {connect} from 'react-redux'
import F from 'lodash/fp'
import MusicSearch from './music-search.jsx'
import MusicRec from './music-rec.jsx'
import {playMusic, puaseMusic, selectMusic} from '../../actions/content-change'

let player = (() => {
    let player = document.createElement('audio')
    player.loop = true
    player.preload = true
    return player
})()

const NoneMusic = props => {
    return (
        <ul>
            <li className={props.selected ? '' : 'selected-music'} onClick={() => props.selectMusic(null)}>
                <span className="music-name">无背景音乐</span>
                <button className="music-wp-ban" type="button"><i className="fa fa-ban" aria-hidden="true"></i></button>
            </li>
            { props.selected 
                ? <li className='selected-music'>
                    <span className="music-name">当前选中：{props.selected.filename}</span>
                </li> 
                : null }
        </ul>
    )
}

const Music = (props) => {
    let ctrl = 
    { pause : F.compose(player.pause.bind(player), props.puaseMusic)
    , play : F.compose(player.play.bind(player), src => player.src = src, F.get('src'), props.playMusic)
    , selected : props.selected
    , selectMusic : props.selectMusic
    }

    return (
        <div className="edit-music-wp">
            <div className="edit-page-title">
                音乐管理
            </div>
            <MusicSearch {...ctrl} />
            <MusicRec {...ctrl} />
            <NoneMusic {...ctrl} />
        </div>
    )
}

export default connect(
    ({music}) => ({
        curSrc: music.curSrc,
        selected: music.selected
    })
    , (dispatch, props) => ({
        playMusic: F.compose(dispatch, playMusic),
        puaseMusic: F.compose(dispatch, puaseMusic),
        selectMusic: F.compose(dispatch, selectMusic),
    })
)(Music)